import pythoncom
from flask import Flask, render_template, request, jsonify, send_file
import os
import requests
import json
import win32com.client as win32
from docx import Document
import PyPDF2
import time

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024  # 16MB

# DeepSeek API配置
DEEPSEEK_API_KEY = "sk-c4a700adf24749f8b660df1aaf2036"
DEEPSEEK_API_URL = "https://api.deepseek.com/v1/chat/completions"

class ContractAnalyzer:
    def __init__(self):
        self.wps_app = None
    def initialize_wps(self):
        """初始化WPS应用程序"""
        try:
            pythoncom.CoInitialize()
            self.wps_app = win32.Dispatch("Kwps.Application")
            self.wps_app.Visible = True  # 调试时可见
            print("WPS应用程序初始化成功")
            return True
        except Exception as e:
            print(f"WPS初始化失败: {e}")
            return False


    def analyze_contract_with_deepseek(self, contract_text):
        """使用DeepSeek分析合同"""
        headers = {
            "Authorization": f"Bearer {DEEPSEEK_API_KEY}",
            "Content-Type": "application/json"
        }

        prompt = f"""作为专业合同审核律师，请分析以下合同内容，找出不合规条款并提供改进建议：
        
合同内容：
{contract_text[:4000]}  # 限制文本长度

请以JSON格式返回结果，包含：
1. non_compliant_clauses: 不合规条款列表，每个条款包含原文、问题描述、风险等级
2. suggestions: 具体改进建议
3. overall_rating: 整体合规评分（0-100）"""

        payload = {
            "model": "deepseek-chat",
            "messages": [{"role": "user", "content": prompt}],
            "temperature": 0.1
        }

        try:
            response = requests.post(DEEPSEEK_API_URL, headers=headers, json=payload, timeout=120)  # 增加超时时间为2分钟
            response.raise_for_status()
            result = response.json()
            print(result['choices'][0]['message']['content'])
            return json.loads(result['choices'][0]['message']['content'])
        except requests.exceptions.Timeout:
            return {"error": "AI分析请求超时，请稍后重试"}

    def add_wps_comments(self, file_path, analysis_results):
        """调试标注功能"""
        if not os.path.exists(file_path):
            print(f"文件不存在: {file_path}")
            return False
        self.initialize_wps()
        try:
            # 打开文档
            print(f"正在打开文档: {file_path}")
            # 确保使用绝对路径打开文件
            absolute_path = os.path.abspath(file_path)
            print(f"绝对路径: {absolute_path}")
            doc = self.wps_app.Documents.Open(absolute_path)
            print("文档打开成功")

            print(type(analysis_results))
            # 处理每个审核结果
            for i, clause in enumerate(analysis_results['non_compliant_clauses']):
                print(type(clause),clause)
                print(f"\n处理第 {i + 1} 个条款:")
                print(f"原文: {clause['原文'][:50]}...")
                print(f"问题: {clause['问题描述'][:50]}...")

                # 提取搜索文本
                yw_text = clause['原文'].strip()
                if not yw_text:
                    print("原文为空，跳过")
                    continue

                # 提取换行符前的文本或前30个字符用于显示
                search_text = yw_text.split('\n')[0][:30] if yw_text else ''

                print(f"搜索文本: {search_text}")
                try:
                    # 创建Find对象
                    find_obj = doc.Content.Find
                    # 设置查找参数 - 忽略所有格式，只搜索纯文本
                    find_obj.ClearFormatting()
                    find_obj.Text = search_text
                    find_obj.Forward = True
                    find_obj.Wrap = 1  # wdFindContinue
                    find_obj.Format = False  # 忽略格式
                    # 执行查找
                    found = find_obj.Execute()
                    if not found:
                        print(search_text[:10])
                        find_obj.Text = search_text[:7]
                        found = find_obj.Execute()

                    if found:
                        print("✓ 找到匹配文本")
                        # 获取找到的范围
                        range = doc.Range(find_obj.Parent.Start, find_obj.Parent.End)
                        comment_text = f"风险等级: {clause['风险等级']}\n问题: {clause['问题描述']}"
                        range.Comments.Add(range, comment_text)
                        print("✓ 注释添加成功")
                    else:
                        print("✗ 未找到匹配文本...")



                except Exception as e:
                    print(f"标注失败: {e}")

            # 保存文档
            doc.Save()
            doc.Close()
            print("\n标注完成，文档已保存")
            return True

        except Exception as e:
            print(f"调试过程中出错: {e}")
            return False

analyzer = ContractAnalyzer()

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/upload', methods=['POST'])
def upload_contract():
    if 'contract' not in request.files:
        return jsonify({'error': '没有上传文件'})

    file = request.files['contract']
    if file.filename == '':
        return jsonify({'error': '没有选择文件'})

    file_path = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
    print(file_path)
    file.save(file_path)

    text_content = extract_text_from_file(file_path)
    print(text_content)
    analysis_result = analyzer.analyze_contract_with_deepseek(text_content)

    if 'error' in analysis_result:
        return jsonify({'error': analysis_result['error']})

    if request.form.get('wps_markup') == 'true':
    # 保存上传文件
        analyzer.add_wps_comments(file_path, analysis_result)

    return jsonify(analysis_result)
    # 提取文本内容
def extract_text_from_file(file_path):
    # AI分析
    if file_path.endswith('.docx'):
        return extract_text_from_docx(file_path)
    elif file_path.endswith('.pdf'):
        return extract_text_from_pdf(file_path)
    elif file_path.endswith('.txt'):
        return extract_text_from_txt(file_path)
    else:
        return "不支持的文件格式"

def extract_text_from_docx(file_path):
    """从不同格式文件中提取文本"""
    doc = Document(file_path)
    return '\n'.join([paragraph.text for paragraph in doc.paragraphs])

def extract_text_from_pdf(file_path):
    text = ""
    with open(file_path, 'rb') as file:
        reader = PyPDF2.PdfReader(file)
        for page in reader.pages:
            text += page.extract_text() + "\n"
    return text

def extract_text_from_txt(file_path):
    """从TXT文件提取文本"""
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            return file.read()
    except UnicodeDecodeError:
        # 如果UTF-8解码失败，尝试其他编码
        with open(file_path, 'r', encoding='gbk') as file:
            return file.read()
    """从DOCX提取文本"""
if __name__ == '__main__':
    if not os.path.exists(app.config['UPLOAD_FOLDER']):
        os.makedirs(app.config['UPLOAD_FOLDER'])
    app.run(debug=True, port=5001)
    """从PDF提取文本"""

